<?php
/**
 *房源
 */

namespace app\admin\controller;

use app\admin\model\HouseType;
use app\admin\model\Region;
use app\common\controller\AdminController;
use app\admin\model\HouseAuction as HouseAuctionModel;
use custom\ImportHouse;
use think\Exception;
use app\admin\model\House as HouseModel;
use think\facade\Request;

class House extends AdminController {

    public $levelConfig = [
        1 => ['houselist', 'wherelist', 'houseinfo', 'addlogget', 'editlogget', 'editinfoget', 'addhouseget'],
        2 => ['onshelf', 'offshelf', 'del', 'addlogpost', 'editlogpost', 'editinfopost', 'addhousepost', 'setimportant','cancelimportant'],
        4 => ['exporthouse'],
        8 => ['importhouse']
    ];

    public $resubmitLock = ['addlogpost', 'editlogpost', 'editinfopost', 'addhousepost', 'setimportant','cancelimportant'];

    /**
     * 房源列表
     * @return false|string
     */
    public function houseList() {
        try {
            $params = $this->checkParams('type,page,long');
            if ($params === false) return $this->resErr();
            HouseModel::getList($params, $data, $page, $pageNum, $count);
            return $this->resData('success', compact('page', 'pageNum', 'count', 'data'));
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 条件数据
     * @return false|string
     */
    public function whereList() {
        try {
            $params = $this->checkParams('');
            if ($params === false) return $this->resErr();
            $area = Region::where('p_code', $params['city_code'])
                ->field('city_code,name')
                ->order('weights', 'asc')
                ->select();
            foreach ($area as $k1 => $v1) {
                $area[$k1]['key'] = $v1['city_code'];
                $area[$k1]['value'] = $v1['name'];
                unset($area[$k1]['city_code']);
                unset($area[$k1]['name']);
            }
            $a_type = HouseModel::$whereList['a_type'];
            $a_status = HouseModel::$whereList['a_status'];
            $bedroom = HouseModel::$whereList['bedroom'];
//            $bulu = HouseModel::$whereList['bulu'];
            $discount = HouseModel::allIntervel($params['city_code'])['discount_interval'];
            $house_floor = HouseModel::allIntervel($params['city_code'])['house_floor'];
            $source_type = HouseModel::$whereList['source_type'];
            $house_type = HouseType::getList();
            $other = HouseModel::$whereList['other'];
            $order = HouseModel::$whereList['order'];
            $export_field = HouseModel::getExportField();
            return $this->resData('success', compact('area', 'a_type', 'a_status', 'bedroom', 'discount', 'house_floor', 'source_type', 'house_type', 'other', 'order', 'export_field'));
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 房源详情
     * @return false|string
     */
    public function houseInfo() {
        try {
            $params = $this->checkParams('id');
            if ($params === false) return $this->resErr();
            $data = HouseModel::houseInfo($params);//房源详情
            if (!$data) return $this->resErr();
            $history = HouseAuctionModel::getHistory($params['id']);//拍卖纪录
            return $this->resData('success', compact('data', 'history'));
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 上架
     * @return false|string
     */
    public function onShelf() {
        try {
            $params = $this->checkParams('ids');
            if ($params === false) return $this->resErr();
            $params['type'] = 1;
            $res = HouseModel::edit_is_shelf($params, $msg);
            if ($res) return $this->resData($msg, []);
            else return $this->resErr();
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 下架
     * @return false|string
     */
    public function offShelf() {
        try {
            $params = $this->checkParams('ids');
            if ($params === false) return $this->resErr();
            $params['type'] = 0;
            $res = HouseModel::edit_is_shelf($params, $msg);
            if ($res) return $this->resData($msg, []);
            else return $this->resErr();
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 删除
     * @return false|string
     */
    public function del() {
        try {
            $params = $this->checkParams('id');
            if ($params === false)
                return $this->resErr();
            $res = HouseModel::del($params['id']);
            if ($res) {
                return $this->resData('操作成功', []);
            } else {
                return $this->resErr();
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 添加拍卖纪录获取
     * @return false|string
     */
    public function addLogGet() {
        try {
            $params = $this->checkParams('action_id');
            if ($params === false) return $this->resErr();
            $res = HouseAuctionModel::is_add($params);
            if (!$res) return $this->resErr();
            $a_type = HouseModel::$whereList['a_type'];//拍卖阶段
            $source_type = HouseModel::$whereList['source_type'];//房源来源
            $auction_status = HouseModel::$whereList['a_status'];//拍卖状态
            return $this->resData('success', compact('a_type', 'source_type', 'auction_status'));
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 添加拍卖纪录提交
     * @return false|string
     */
    public function addLogPost() {
        try {
            $params = $this->checkParams('action_id,type,start_time,end_time,initial_price,price_lower_offset,source_type,source_url,source_id,auction_status');
            if ($params === false) return $this->resErr();
            $re = HouseAuctionModel::editlog($params);
            if (!$re) {
                return $this->resErr();
            } else {
                return $this->resData('添加成功', []);
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 编辑拍卖纪录获取
     * @return false|string
     */
    public function editLogGet() {
        try {
            $params = $this->checkParams('history_id');
            if ($params === false) return $this->resErr();
            $res = HouseAuctionModel::is_end([['id', '=', $params['history_id']]], 'auction_status');
            if (!$res) return $this->resErr();
            $column = ['type,start_time,end_time,initial_price,consult_price,market_price,price_lower_offset,court_name,contact_name,contact_tel,source_type,source_id,source_url,auction_status,bond,tail_money_date,enroll_num,access_num,remind_num'];
            $info = HouseAuctionModel::getOne([['id', '=', $params['history_id']]], $column);
            $info = HouseAuctionModel::dealTimeAndMoney($info);
            $a_type = HouseModel::$whereList['a_type'];//拍卖阶段
            $source_type = HouseModel::$whereList['source_type'];//房源来源
            $auction_status = HouseModel::$whereList['a_status'];//拍卖状态
            return $this->resData('success', compact('a_type', 'source_type', 'info', 'auction_status'));
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 编辑拍卖纪录获取
     * @return false|string
     */
    public function editLogPost() {
        try {
            $params = $this->checkParams('history_id,type,start_time,end_time,initial_price,price_lower_offset,source_type,source_url,source_id,auction_status');
            if ($params === false)
                return $this->resErr();
            $params['action_id'] = $params['history_id'];
            $re = HouseAuctionModel::editlog($params);
            if (!$re) {
                return $this->resErr();
            } else {
                return $this->resData('编辑成功', []);
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 房源详情编辑获取
     * @return false|string
     */
    public function editInfoGet() {
        try {
            $params = $this->checkParams('id');
            if ($params === false) return $this->resErr();
            //详情
            $info = HouseModel::editInfoGet($params);
            if (!$info) return $this->resErr();
            //市区商圈
            $houseCity = config('global.house_city_all');
            $houseCity = Region::cityAreabusiness($houseCity);
            $houseType = db('house_type')->field('id,name')->select();//房屋类型
            foreach ($houseType as $k1 => $v1) {
                $houseType[$k1]['key'] = $houseType[$k1]['id'];
                $houseType[$k1]['value'] = $houseType[$k1]['name'];
                unset($houseType[$k1]['id']);
                unset($houseType[$k1]['name']);
            }
            $houseCate = HouseModel::$whereList['house_cate'];//房屋分类
            $lifts = HouseModel::$whereList['lifts'];//楼梯
            $livingType = HouseModel::$whereList['living_type'];//居住情况
            $renovationType = HouseModel::$whereList['renovation_type'];//装修类型
            $propertyType = HouseModel::$whereList['property_type'];//产权类型
            return $this->resData('success', compact('info', 'houseCity', 'houseType', 'houseCate', 'lifts', 'livingType', 'renovationType', 'propertyType'));
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 房源详情编辑提交
     * @return false|string
     */
    public function editInfoPost() {
        try {
            $params = $this->checkParams('id,city_code,area_code,address,house_type,build_area,lifts,living_type,renovation_type,pic');
            if ($params === false) return $this->resErr();
            $res = HouseModel::editinfo($params, $msg);
            if (!$res) {
                return $this->resErr();
            } else return $this->resData($msg, []);
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 新增房源获取
     * @return false|string
     */
    public function addHouseGet() {
        try {
            $params = $this->checkParams('');
            if ($params === false)
                return $this->resErr();
            //市区商圈
            $houseCity = config('global.house_city_all');
            $houseCity = Region::cityAreabusiness($houseCity);
            $houseType = db('house_type')->field('id,name')->select();//房屋类型
            foreach ($houseType as $k1 => $v1) {
                $houseType[$k1]['key'] = $houseType[$k1]['id'];
                $houseType[$k1]['value'] = $houseType[$k1]['name'];
                unset($houseType[$k1]['id']);
                unset($houseType[$k1]['name']);
            }
            $houseCate = HouseModel::$whereList['house_cate'];//房屋分类
            $lifts = HouseModel::$whereList['lifts'];//楼梯
            $livingType = HouseModel::$whereList['living_type'];//居住情况
            $renovationType = HouseModel::$whereList['renovation_type'];//装修类型
            $propertyType = HouseModel::$whereList['property_type'];//产权类型
            $a_type = HouseModel::$whereList['a_type'];
            $source_type = HouseModel::$whereList['source_type'];   //来源类型
            $auction_status = HouseModel::$whereList['a_status'];//拍卖状态
            return $this->resData('success', compact('houseCity', 'houseType', 'houseCate', 'lifts', 'livingType', 'renovationType', 'propertyType', 'a_type', 'source_type', 'auction_status'));
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 新增房源提交
     * @return false|string
     */
    public function addHousePost() {
        try {
            $params = $this->checkParams('title,city_code,area_code,address,house_type,build_area,lifts,living_type,renovation_type,pic,type,start_time,end_time,initial_price,price_lower_offset,source_type,source_url,source_id,auction_status');
            if ($params === false)
                return $this->resErr();
            $res = HouseModel::addHouse($params);
            if (!$res) {
                return $this->resErr();
            } else {
                return $this->resData('添加成功,它被保存到下架房源', []);
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 房源导入
     * @return false|string
     */
    public function importHouse() {
        try {
            $params = $this->checkParams('');
            $file = $_FILES['file'];
            $config = [
                'ext'  => ['csv'],
                'size' => 6 * 1024 * 1024,
            ];
            $importHouse = new ImportHouse($file, $config, $this->uInfo['id'], $params['city_code']);
            if (!$importHouse->import()) {
                return $this->resErr();
            }

            return $this->resData('success', []);
        } catch (Exception $e) {
            return $this->resErr($e->getMessage());
        }

    }

    /**
     * 房源导出数据处理
     * @return false|string
     */
    public function exportHouse() {
        try {
            $params = $this->checkParams('type,field');
            if ($params === false) return $this->resErr();
            if (!$key = HouseModel::exportData($params)) {
                return $this->resErr();
            }
            $key = base64_encode(get_nonce_str(16) . $key);
            return $this->resData('success', ['url' => "export/exporthouse.json?key={$key}"]);
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 设置重点房源
     * @return false|string
     */
    public function setImportant() {
        try {
            if (Request::isGet()) {
                $params = $this->checkParams('id');
                if ($params === false) return $this->resErr();
                $res = HouseModel::setImportant($params,1);
                if (!$res) return $this->resErr();
                else return $this->resData('设置成功', []);
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 取消重点房源
     * @return false|string
     */
    public function cancelImportant() {
        try {
            if (Request::isGet()) {
                $params = $this->checkParams('id');
                if ($params === false) return $this->resErr();
                $res = HouseModel::setImportant($params,0);
                if (!$res) return $this->resErr();
                else return $this->resData('设置成功', []);
            }
        } catch (Exception $e) {
            return $this->resErr($e->getMessage(), $e->getCode());
        }
    }
}
